﻿using System;
using System.Web;
namespace Ue.Qcdz.UI.Controller
{
    /// <summary>
    /// 上传图片（未开发好的）
    /// </summary>
    public class UploadFileController : Ue.Infrastructure.Web.AsyncHandlers.AsyncHandler
    {
        string folder = string.Empty;
        HttpPostedFile file;
        string uploadpath = string.Empty;
        public UploadFileController(AsyncCallback callback, HttpContext context, object state)
        {
            string action = context.Request["Action"];
            folder = context.Request["folder"];
            if (context.Request.Files.Count > 0)
                file = context.Request.Files[0];
            uploadpath = context.Server.MapPath(folder + "\\" + DateTime.Now.ToShortDateString() + "\\");

            //uploadify控件的上传
            if (action == "uploadify")
                SaveUploadifyFile(context);
        }

        public string SaveFile()
        {

            if (file != null)
            {
                if (!System.IO.Directory.Exists(uploadpath))
                {
                    System.IO.Directory.CreateDirectory(uploadpath);
                }
                string strNewFileName = GetNewFileName(file.FileName);
                file.SaveAs(uploadpath + strNewFileName);


                return (folder + '/' + DateTime.Now.ToShortDateString() + "/" + strNewFileName);
            }
            else
            {
                return "0";
            }
        }



        /// <summary>
        /// 此方法 只用于  Uploadify 控件 的上传
        /// </summary>
        private void SaveUploadifyFile(HttpContext context)
        {
            if (file != null)
            {
                if (!System.IO.Directory.Exists(uploadpath))
                {
                    System.IO.Directory.CreateDirectory(uploadpath);
                }
                string strNewFileName = GetNewFileName(file.FileName);
                file.SaveAs(uploadpath + strNewFileName);
                context.Response.Write(folder + '/' + DateTime.Now.ToShortDateString() + "/" + strNewFileName);
            }
            else
            {
                context.Response.Write("0");
            }

        }

        /// <summary>
        /// 根据原文件名 生成 随机文件名
        /// </summary>
        /// <param name="FileName">原文件名</param>
        /// <returns>新的文件名</returns>
        private string GetNewFileName(string FileName)
        {
            string newfilename = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString()
            + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString()
            + DateTime.Now.Second.ToString() + DateTime.Now.Minute.ToString()
            + DateTime.Now.Millisecond.ToString()
                //+ rand.Next(1000).ToString() 
            + FileName.Substring(FileName.LastIndexOf("."), FileName.Length - FileName.LastIndexOf("."));
            return newfilename;
        }

    }
}
